package study.websocket;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class Demo3 {
    // 服务端 URI 列表
    private static final List<String> serverURIs = Arrays.asList(
            "ws://localhost:8082/ws",
            "ws://localhost:8083/ws"
    );

    private static Map<String, main.java.study.websocket.MultiServerWebSocketClient> clientMap = new ConcurrentHashMap<>();
    // 创建线程池
    private static ExecutorService executorService = Executors.newFixedThreadPool(serverURIs.size());
    Demo3() {
        for (String uri : serverURIs) {
            main.java.study.websocket.MultiServerWebSocketClient client = new main.java.study.websocket.MultiServerWebSocketClient(uri);
            clientMap.put(uri, client);
        }
    }
    public static void main(String[] args) throws InterruptedException {



        Demo3 demo = new Demo3();
        while (true) {
            sendMessage();

            // 输出所有服务端返回的结果
            System.out.println("Collected responses: " + main.java.study.websocket.MultiServerWebSocketClient.getResponseList());
            // 清理结果
            main.java.study.websocket.MultiServerWebSocketClient.clearResponseList();
        }


        // 关闭线程池
//        executorService.shutdown();
    }

    private static void sendMessage() {
        // 存储 Future 用于获取结果
        List<Future<Void>> futures = new ArrayList<>();
        System.out.println("size of clientMap: " + clientMap.size());
        // 遍历服务端地址并连接每个服务端
        for (String uri : serverURIs) {
            main.java.study.websocket.MultiServerWebSocketClient client = clientMap.get(uri);

            client.sendMessage("Hello from client");

//            futures.add(executorService.submit(() -> {
//
//                client.sendMessage("Hello from client"); // 发送消息
////                TimeUnit.SECONDS.sleep(5); // 等待响应
//                return null;
//            }));
        }

        // 等待所有任务完成
//        for (Future<Void> future : futures) {
//            try {
//                future.get(); // 确保任务完成
//            } catch (InterruptedException | ExecutionException e) {
//                e.printStackTrace();
//            }
//        }
    }
}
